const $api = require('../../../utils/request').Api;

Page({
  page: {
    pagSize: 10,
    pagNum: 1,
  },

  data: {
    dataList: [],
    listLoading: 0, // 0-未加载，1-加载中，2-已全部加载
    pullDownRefreshing: false, // 下拉刷新时不显示load-more
    emptyImg:
      'https://cdn-we-retail.ym.tencent.com/miniapp/order/empty-order-list.png',
    backRefresh: false,
  },

  onLoad() {
    this.refreshList()
    this.pullDownRefresh = this.selectComponent('#wr-pull-down-refresh');
  },

  onShow() {
    // 当从其他页面返回，并且 backRefresh 被置为 true 时，刷新数据
    if (!this.data.backRefresh) return;
    this.onRefresh();
    this.setData({
      backRefresh: false,
    });
  },

  onReachBottom() {
    console.log(this.data.no);
    if (this.data.listLoading === 0 && !this.data.no) {
      this.getAfterServiceList();
    }
  },

  onPageScroll(e) {
    this.pullDownRefresh && this.pullDownRefresh.onPageScroll(e);
  },

  onPullDownRefresh_(e) {
    console.log(e)
    const callback = e.detail?.callback;
    this.setData({
      pullDownRefreshing: true,
    }); // 下拉刷新时不显示load-more
    this.refreshList(this.data.curTab)
      .then(() => {
        this.setData({
          pullDownRefreshing: false,
        });
        callback && callback();
      })
      .catch((err) => {
        this.setData({
          pullDownRefreshing: false,
        });
        Promise.reject(err);
      });
  },

  getAfterServiceList(reset = false) {
    this.setData({ listLoading: 1 });
    const login = wx.getStorageSync('login')
    return $api.refundList({
      memberNumber: login.data.data.memberNumber,
      ...this.page
    }).then(({ data: res }) => {
      this.page.pagNum++;
      let dataList = [];
      if (res && res.data && res.data.refundList) {
        dataList = (res.data.refundList || []).map(item => ({
          id: item.orderCode,
          // serviceNo: _data.rights.rightsNo,
          // storeName: _data.rights.storeName,
          // type: _data.rights.rightsType,
          typeDesc: item.status,
          typeDescIcon: 'money-circle',
            // _data.rightsType === ServiceType.ONLY_REFUND
            //   ? 'money-circle'
            //   : 'return-goods-1',
          // status: _data.rights.rightsStatus,
          // statusName: _data.rights.userRightsStatusName,
          // statusDesc: _data.rights.userRightsStatusDesc,
          amount: item.amount,
          goodsList: item.goodsInfo.map((item, i) => ({
            id: item.orderCode,
            imgUrl: item.imgurl,
            productTitle: item.productTitle,
            // specs: (item.specInfo || []).map((s) => s.specValues || ''),
            itemRefundAmount: item.price,
            rightsQuantity: item.count,
            price: (item.count * item.price).toFixed(2)
          })),
          // storeId: _data.storeId,
          // buttons: _data.buttonVOs || [],
          // logisticsNo: _data.logisticsVO.logisticsNo, // 退货物流单号
          // logisticsCompanyName: _data.logisticsVO.logisticsCompanyName, // 退货物流公司
          // logisticsCompanyCode: _data.logisticsVO.logisticsCompanyCode, // 退货物流公司
          remark: item.cause, // 退货备注
          // logisticsVO: _data.logisticsVO,
        }));
        this.data.no = this.page.pagSize > res.data.refundList.length
      }
      return new Promise((resolve) => {
        if (reset) {
          this.setData(
            {
              dataList: [],
              totalPages: Math.ceil(res.data.total / this.page.pageSize), // 设置总页数

            },
            () => resolve(),
          );
        } else resolve();
      }).then(() => {
        // if (!reset) {
        //   // 已经到达最后一页，不再添加数据
        //   this.setData({
        //     listLoading: 0,
        //   });
        // } else {
          
        // }
        this.setData({
          dataList: this.data.dataList.concat(dataList.reduce((acc, curr) => {
            const found = acc.find(item => item.id === curr.id); // 根据id判断是否已存在相同数据
            if (!found) {
              acc.push(curr); // 不存在则添加到新数组中
            }
            return acc;
          }, [])),
          listLoading: dataList.length > 0 ? 0 : 2,
        });
     
      });
    })
      .catch((err) => {
        this.setData({
          listLoading: 3,
        });
        return Promise.reject(err);
      });
  },

  onReTryLoad() {
    this.getAfterServiceList();
  },

  refreshList() {
    this.page = {
      pagSize: 10,
      pagNum: 1,
    };
    this.setData({ dataList: [] });
    return this.getAfterServiceList(true);
  },

  onRefresh() {
    this.refreshList(this.data.curTab);
  },

  // 点击订单卡片
  onAfterServiceCardTap(e) {
    // wx.navigateTo({
    //   url: `/pages/order/after-service-detail/index?rightsNo=${e.currentTarget.dataset.order.id}`,
    // });
  },
});
